package com.example.hhh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hhh.model.pojo.Customer;
import com.example.hhh.service.CustomerService;
import com.example.hhh.mapper.CustomerMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 客户管理控制器
 */
@RestController
@RequestMapping("/api/customer")
@CrossOrigin(origins = "*")
public class CustomerController {

    @Autowired
    private CustomerService customerService;
    
    @Autowired
    private CustomerMapper customerMapper;

    /**
     * Excel批量导入客户数据
     */
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importCustomers(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "请选择文件");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 校验Excel表头
            List<String> expectedHeaders = List.of("客户名称", "联系电话", "联系邮箱", "地址", "客户等级", "行业类型", "客户来源", "状态", "备注", "创建时间", "更新时间");
            List<String> actualHeaders = readExcelHeaders(file);
            
            if (!actualHeaders.equals(expectedHeaders)) {
                result.put("success", false);
                result.put("message", "Excel模板不正确！请使用客户导入模板，表头必须包含：" + String.join(", ", expectedHeaders));
                return ResponseEntity.badRequest().body(result);
            }
            
            List<Customer> customers = readExcelFile(file);
            int successCount = 0;
            List<String> errors = new ArrayList<>();
            
            for (int i = 0; i < customers.size(); i++) {
                try {
                    Customer customer = customers.get(i);
                    
                    // 验证必填字段
                    if (customer.getCustomerName() == null || customer.getCustomerName().trim().isEmpty()) {
                        errors.add("第" + (i + 2) + "行：客户名称不能为空");
                        continue;
                    }
                    
                    // 检查客户名称是否重复
                    QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("customer_name", customer.getCustomerName().trim());
                    Customer existingCustomer = customerService.getOne(queryWrapper);
                    if (existingCustomer != null) {
                        errors.add("第" + (i + 2) + "行：客户名称'" + customer.getCustomerName().trim() + "'已存在，跳过导入");
                        continue;
                    }
                    
                    customer.setCreateTime(new Date());
                    customer.setUpdateTime(new Date());
                    
                    // 打印调试信息
                    System.out.println("正在导入第" + (i + 2) + "行客户数据：" + customer.toString());
                    
                    // 检查插入结果
                    int insertResult = customerMapper.insert(customer);
                    System.out.println("第" + (i + 2) + "行插入结果：" + insertResult);
                    
                    if (insertResult > 0) {
                        successCount++;
                        System.out.println("第" + (i + 2) + "行导入成功");
                    } else {
                        errors.add("第" + (i + 2) + "行：数据库插入失败");
                        System.out.println("第" + (i + 2) + "行导入失败：插入返回0");
                    }
                } catch (Exception e) {
                    errors.add("第" + (i + 2) + "行导入失败：" + e.getMessage());
                    System.out.println("第" + (i + 2) + "行导入异常：" + e.getMessage());
                    e.printStackTrace(); // 打印详细错误信息到控制台
                }
            }
            
            result.put("success", successCount > 0 || errors.isEmpty()); // 只有真正有成功插入或没有错误才算成功
            result.put("successCount", successCount);
            result.put("errorCount", errors.size());
            result.put("errors", errors);
            result.put("message", "导入完成，成功" + successCount + "条，失败" + errors.size() + "条");
            result.put("totalProcessed", customers.size()); // 添加处理总数信息
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "导入失败：" + e.getMessage());
            java.io.StringWriter sw = new java.io.StringWriter();
            e.printStackTrace(new java.io.PrintWriter(sw));
            result.put("stackTrace", sw.toString());
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 读取Excel表头
     */
    private List<String> readExcelHeaders(MultipartFile file) throws IOException {
        List<String> headers = new ArrayList<>();
        
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            Row headerRow = sheet.getRow(0);
            
            if (headerRow != null) {
                for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                    Cell cell = headerRow.getCell(i);
                    if (cell != null) {
                        headers.add(cell.toString().trim());
                    } else {
                        headers.add("");
                    }
                }
            }
        }
        
        return headers;
    }
    
    /**
     * 读取Excel文件
     */
    private List<Customer> readExcelFile(MultipartFile file) throws IOException {
        List<Customer> customers = new ArrayList<>();
        
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                
                Customer customer = new Customer();
                
                // 客户名称
                Cell nameCell = row.getCell(0);
                if (nameCell != null && !nameCell.toString().trim().isEmpty()) {
                    customer.setCustomerName(nameCell.toString().trim());
                } else {
                    continue; // 跳过空行
                }
                
                // 联系电话
                Cell phoneCell = row.getCell(1);
                if (phoneCell != null) {
                    customer.setContactPhone(phoneCell.toString().trim());
                }
                
                // 联系邮箱
                Cell emailCell = row.getCell(2);
                if (emailCell != null) {
                    customer.setContactEmail(emailCell.toString().trim());
                }
                
                // 地址
                Cell addressCell = row.getCell(3);
                if (addressCell != null) {
                    customer.setAddress(addressCell.toString().trim());
                }
                
                // 客户等级
                Cell levelCell = row.getCell(4);
                if (levelCell != null) {
                    try {
                        customer.setCustomerLevel((int) levelCell.getNumericCellValue());
                    } catch (Exception e) {
                        customer.setCustomerLevel(1); // 默认等级
                    }
                }
                
                // 行业类型
                Cell industryCell = row.getCell(5);
                if (industryCell != null) {
                    customer.setIndustryType(industryCell.toString().trim());
                }
                
                // 客户来源
                Cell sourceCell = row.getCell(6);
                if (sourceCell != null) {
                    customer.setSource(sourceCell.toString().trim());
                }
                
                // 状态
                Cell statusCell = row.getCell(7);
                if (statusCell != null) {
                    try {
                        customer.setStatus((int) statusCell.getNumericCellValue());
                    } catch (Exception e) {
                        customer.setStatus(1); // 默认活跃
                    }
                } else {
                    customer.setStatus(1);
                }
                
                // 备注
                Cell remarkCell = row.getCell(8);
                if (remarkCell != null) {
                    customer.setRemark(remarkCell.toString().trim());
                }
                
                // 设置时间字段
                customer.setCreateTime(new Date());
                customer.setUpdateTime(new Date());
                
                customers.add(customer);
            }
        }
        
        return customers;
    }

    // 新增
    @PostMapping
    public ResponseEntity<Map<String, Object>> addCustomer(@RequestBody Customer customer) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证必填字段
            if (customer.getCustomerName() == null || customer.getCustomerName().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "客户名称不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查客户名称是否重复
            QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("customer_name", customer.getCustomerName().trim());
            Customer existingCustomer = customerService.getOne(queryWrapper);
            if (existingCustomer != null) {
                result.put("success", false);
                result.put("message", "客户名称'" + customer.getCustomerName().trim() + "'已存在");
                return ResponseEntity.badRequest().body(result);
            }
            
            customer.setCreateTime(new Date());
            customer.setUpdateTime(new Date());
            
            boolean success = customerService.save(customer);
            result.put("success", success);
            result.put("message", success ? "客户添加成功" : "客户添加失败");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加客户失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }

    // 删除
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteCustomer(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = customerService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败，数据不存在或有关联数据");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    // 修改
    @PutMapping
    public boolean updateCustomer(@RequestBody Customer customer) {
        customer.setUpdateTime(new Date());
        return customerService.updateById(customer);
    }

    // 查询单个
    @GetMapping("/{id}")
    public Customer getCustomer(@PathVariable Integer id) {
        return customerService.getById(id);
    }

    // 查询所有
    @GetMapping("/list")
    public Map<String, Object> getAllCustomer(@RequestParam(defaultValue = "1") Integer page,
                                              @RequestParam(defaultValue = "12") Integer limit,
                                              @RequestParam(required = false) String search) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
            if (search != null && !search.trim().isEmpty()) {
                queryWrapper.like("customer_name", search.trim())
                           .or()
                           .like("contact_phone", search.trim())
                           .or()
                           .like("contact_email", search.trim());
            }
            
            Page<Customer> pageParam = new Page<>(page, limit);
            IPage<Customer> pageResult = customerService.page(pageParam, queryWrapper);
            
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("pages", pageResult.getPages());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());
            
        } catch (Exception e) {
            result.put("records", new ArrayList<>());
            result.put("total", 0);
            result.put("pages", 0);
            result.put("current", page);
            result.put("size", limit);
        }
        
        return result;
    }

    // 分页查询
    @GetMapping("/page")
    public IPage<Customer> getCustomerPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Customer> page = new Page<>(pageNum, pageSize);
        return customerService.page(page, new QueryWrapper<>());
    }

    /**
     * 获取本月新增客户数量
     */
    @GetMapping("/monthly-new")
    public ResponseEntity<Map<String, Object>> getMonthlyNewCustomers() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取本月的开始和结束时间
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date monthStart = calendar.getTime();
            
            calendar.add(Calendar.MONTH, 1);
            calendar.add(Calendar.MILLISECOND, -1);
            Date monthEnd = calendar.getTime();
            
            System.out.println("本月开始时间: " + monthStart);
            System.out.println("本月结束时间: " + monthEnd);
            
            // 查询本月新增的客户数量
            QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
            queryWrapper.between("create_time", monthStart, monthEnd);
            long monthlyNewCount = customerService.count(queryWrapper);
            
            System.out.println("本月新增客户数量: " + monthlyNewCount);
            
            result.put("success", true);
            result.put("monthlyNewCount", monthlyNewCount);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取本月新增客户数量失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(result);
    }

    /**
     * 导出客户数据到Excel
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportCustomers() {
        try {
            List<Customer> customers = customerService.list();
            
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("客户信息");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] excelHeaders = {"客户名称", "联系电话", "联系邮箱", "地址", "客户等级", "行业类型", "客户来源", "状态", "备注", "创建时间", "更新时间"};
            for (int i = 0; i < excelHeaders.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(excelHeaders[i]);
            }
            
            // 填充数据
            for (int i = 0; i < customers.size(); i++) {
                Customer customer = customers.get(i);
                Row row = sheet.createRow(i + 1);
                
                row.createCell(0).setCellValue(customer.getCustomerName() != null ? customer.getCustomerName() : "");
                row.createCell(1).setCellValue(customer.getContactPhone() != null ? customer.getContactPhone() : "");
                row.createCell(2).setCellValue(customer.getContactEmail() != null ? customer.getContactEmail() : "");
                row.createCell(3).setCellValue(customer.getAddress() != null ? customer.getAddress() : "");
                row.createCell(4).setCellValue(customer.getCustomerLevel() != null ? customer.getCustomerLevel() : 1);
                row.createCell(5).setCellValue(customer.getIndustryType() != null ? customer.getIndustryType() : "");
                row.createCell(6).setCellValue(customer.getSource() != null ? customer.getSource() : "");
                row.createCell(7).setCellValue(customer.getStatus() != null ? customer.getStatus() : 1);
                row.createCell(8).setCellValue(customer.getRemark() != null ? customer.getRemark() : "");
                row.createCell(9).setCellValue(customer.getCreateTime() != null ? customer.getCreateTime().toString() : "");
                row.createCell(10).setCellValue(customer.getUpdateTime() != null ? customer.getUpdateTime().toString() : "");
            }
            
            // 自动调整列宽
            for (int i = 0; i < excelHeaders.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            workbook.close();
            
            byte[] bytes = outputStream.toByteArray();
            
            // 保存到桌面daochu目录
            String desktopPath = System.getProperty("user.home") + "/Desktop/daochu";
            File dir = new File(desktopPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            String fileName = "客户信息_" + System.currentTimeMillis() + ".xlsx";
            File file = new File(dir, fileName);
            try (FileOutputStream fileOut = new FileOutputStream(file)) {
                fileOut.write(bytes);
            }
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
            
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 测试数据库连接和插入操作
     */
    @PostMapping("/test-insert")
    public ResponseEntity<Map<String, Object>> testInsert() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Customer testCustomer = new Customer();
            testCustomer.setCustomerName("测试客户_" + System.currentTimeMillis());
            testCustomer.setContactPhone("13800138000");
            testCustomer.setContactEmail("test@example.com");
            testCustomer.setAddress("测试地址");
            testCustomer.setCustomerLevel(1);
            testCustomer.setIndustryType("测试行业");
            testCustomer.setSource("测试来源");
            testCustomer.setStatus(1);
            testCustomer.setRemark("测试备注");
            testCustomer.setCreateTime(new Date());
            testCustomer.setUpdateTime(new Date());
            
            System.out.println("测试插入客户数据：" + testCustomer.toString());
            
            int insertResult = customerMapper.insert(testCustomer);
            System.out.println("测试插入结果：" + insertResult);
            
            result.put("success", insertResult > 0);
            result.put("message", insertResult > 0 ? "测试插入成功" : "测试插入失败");
            result.put("insertResult", insertResult);
            result.put("customerId", testCustomer.getCustomerId());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "测试插入失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return ResponseEntity.ok(result);
    }
}
